package com.wangsd.web.api.controller;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wangsd.common.basicbean.MyController;
import com.wangsd.common.basicbean.Result;
import com.wangsd.common.component.WxMiniService;
import com.wangsd.common.utils.DateUtils;
import com.wangsd.common.utils.HttpClientUtils;
import com.wangsd.common.utils.MD5Utils;
import com.wangsd.web.shop.entity.*;
import com.wangsd.web.shop.service.*;
import com.wangsd.web.sys.entity.SysCompany;
import com.wangsd.web.sys.entity.UploadFile;
import com.wangsd.web.sys.service.SysCompanyService;
import com.wangsd.web.sys.service.UploadFileService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;


@Api(tags = "接口管理")
@RestController
@RequestMapping("/api/user")
@Slf4j
public class MiniUserController extends MyController {
    @Value("${notify_url}")
    private String notify_url;
    @Autowired
    CustomerService customerService;
    @Autowired
    UploadFileService uploadFileService;
    @Autowired
    MemberService memberService;
    @Autowired
    CouponService couponService;
    @Autowired
    SysCompanyService companyService;
    @Autowired
    MerchantService merchantService;
    @Autowired
    CouponOrderService couponOrderService;
    @Autowired
    ActivityService activityService;
    @Autowired
    TradeService tradeService;
    @Autowired
    MemberIntegralService memberIntegralService;

    @GetMapping("/webAuthorize")
    public void webAuthorize(String miniAppid, String miniAccessToken) {
        log.debug("进入网页授权:miniAppid={},miniAccessToken={}", miniAppid, miniAccessToken);
        Customer customer = customerService.selectByMiniAppid(miniAppid);
        String[] codes = customer.getParentCode().split("-");
        SysCompany company = companyService.selectByCode(codes[0]);
        String callBack = notify_url + "/api/notify/webOpenid";
        String redirect = "https://wechat.alipayjf.com/api/open/authorize?appid=" + company.getWxAppId()
                + "&from=" + callBack + "&state=" + miniAccessToken;
        try {
            response.sendRedirect(redirect);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/isWebAuthorize")
    public Result isWebAuthorize() {
        Member loginMember = this.getMiniUserInfo();
        return Result.success(loginMember);
    }

    @RequestMapping("/login")
    public Result login(String code) {
        Customer customer = customerService.selectByMiniAppid(this.getMiniAppid());
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        url +="?appid=" + this.getMiniAppid() +
                "&secret=" + customer.getMiniSecret() +
                "&js_code=" + code +
                "&grant_type=authorization_code";
//        WxMiniService wxMiniService = new WxMiniService(this.getMiniAppid(), customer.getMiniSecret());
//        WxMaJscode2SessionResult data = wxMiniService.login(code);
        String str = HttpClientUtils.get(url);
        JSONObject json = JSON.parseObject(str);
        Member member = new Member();
        member.setMiniOpenid(json.getString("openid"));
        member.setSessionKey(json.getString("session_key"));
        String token = StringUtils.replace(UUID.randomUUID().toString(), "-", "");
        redisTemplate.opsForValue().set(token, member, 24, TimeUnit.HOURS);

        Map map = new HashMap();
        map.put("miniOpenid", json.getString("openid"));
        map.put("token", token);
        map.put("customerName", customer.getName());
        return Result.success(map);
    }

    /**
     * 保存会员信息相当于注册
     * @param member
     * @return
     */
    @RequestMapping("/saveMember")
    public Result saveMember(@RequestBody Member member) {
        Customer customer = customerService.selectByMiniAppid(this.getMiniAppid());
        WxMiniService wxMiniService = new WxMiniService(this.getMiniAppid(), customer.getMiniSecret());
        Member loginMember = getMiniUserInfo();
        WxMaPhoneNumberInfo data = wxMiniService.getPhoneNoInfo(loginMember.getSessionKey(), member.getEncryptedData(), member.getIvStr());

        member.setMobile(data.getPhoneNumber());
        member.setMiniOpenid(loginMember.getMiniOpenid());
        member.setParentCode(customer.getCode());
        memberService.register(member);
        return Result.success(data.getPhoneNumber());
    }

    /**
     * 查询我的优惠券
     * @return
     */
    @GetMapping("/selectMyCouponList")
    public Result selectMyCouponList(Integer status) {
        Member loginMerber = this.getMiniUserInfo();
        List<CouponOrder> list = couponOrderService.selectByMiniOpenid(loginMerber.getMiniOpenid(), status);
        return Result.success(list);
    }

    /**
     * 查询会员信息
     * @return
     */
    @GetMapping("/selectMember")
    public Result selectMember() {
        Member loginMerber = this.getMiniUserInfo();
        loginMerber = memberService.selectByMiniOpenId(loginMerber.getMiniOpenid());
        List<CouponOrder> list = couponOrderService.selectByMiniOpenid(loginMerber.getMiniOpenid(), 1);
        loginMerber.setCouponList(list);
        return Result.success(loginMerber);
    }

    /**
     * 查询我的订单
     * @param status
     * @return
     */
    @GetMapping("/selectMyOrderLit")
    public Result selectMyOrderLit(Integer status) {
        Member loginMerber = this.getMiniUserInfo();
        List<Trade> list = tradeService.selectByMiniOpenid(loginMerber.getMiniOpenid(), status);
        return Result.success(list);
    }

    /**
     * 待支付订单二次支付
     * @param tradeId
     * @return
     */
    @GetMapping("/payTradeStatus0")
    public Result payTradeStatus0(Long tradeId) {
        Trade trade = tradeService.selectById(tradeId);
        return Result.success();
    }

    /**
     * 查询积分明细
     * @return
     */
    @GetMapping("/selectIntegral")
    public Result selectIntegral() {
        Member loginMerber = this.getMiniUserInfo();
        List<MemberIntegral> list = memberIntegralService.selectByMiniOpenid(loginMerber.getMiniOpenid());
        return Result.success(list);
    }
}
